//
//  ZYGcdBarrierTest.m
//  OC_Principle
//
//  Created by wangzhipan on 2025/2/18.
//

#import "ZYGcdBarrierTest.h"
/*
 利用dispatch_barrier_async实现多读单写
 */
@interface ZYGcdBarrierTest() {
    dispatch_queue_t _queue;
    int _age;
}
@end

@implementation ZYGcdBarrierTest
- (instancetype)init
{
    if (self = [super init]) {
        _queue = dispatch_queue_create("rw_queue", DISPATCH_QUEUE_CONCURRENT);
        _age = 0;
    }
    return self;
}

- (void)setup
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self write:10];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self write:15];
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self read];
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self read];
    });
}

- (void)read
{
    dispatch_async(_queue, ^{
        sleep(1);
        NSLog(@"%s:: %d", __func__, self->_age);
    });
}

- (void)write:(int)x
{
    //dispatch_barrier_async：会阻拦_queue中其他任务执行，直到barrier_async任务执行完
    dispatch_barrier_async(_queue, ^{
        sleep(2);
        self->_age = x;
        NSLog(@"%s:: %d", __func__, self->_age);
    });
}
@end
